import classNames from 'classnames'
import React, { Component } from 'react'
import dayjs from 'dayjs'

export default class List extends Component {
  handleClick = (id) => {
    this.props.delComment(id)
  }
  // !#2 子组件调用传递过来方法的同时并传递参数
  handleLike = (id, attitude) => {
    this.props.likeComment(id, attitude)
  }
  render() {
    const { list, active } = this.props
    // 排序思路 2：根据 active 的值是 'time' 或 'hot'，对 list 进行排序
    // 但是不是直接修改 list 数据（拷贝一份 list 进行修改，渲染的是拷贝之后的 list）
    const tempList = JSON.parse(JSON.stringify(list))
    // 上面深拷贝搞不定日期对象，会把日期对象转成字符串
    if (active === 'time') {
      tempList.sort(
        (item1, item2) => new Date(item2.time) - new Date(item1.time)
      )
    } else if (active === 'hot') {
      tempList.sort((item1, item2) => item2.id - item1.id)
    }
    return (
      <div className='comment-list'>
        {/* //!注意渲染的是一定是 tempList */}
        {tempList.map((item) => (
          <div className='list-item' key={item.id}>
            <div className='user-face'>
              <img className='user-head' src={item.img} alt='' />
            </div>
            <div className='comment'>
              <div className='user'>{item.author}</div>
              <p className='text'>{item.comment}</p>
              <div className='info'>
                <span className='time'>
                  {dayjs(item.time).format('YYYY-MM-DD HH:mm:ss')}
                </span>
                <span
                  className={classNames('like', {
                    liked: item.attitude === 1,
                  })}
                  onClick={() =>
                    this.handleLike(item.id, item.attitude === 1 ? 0 : 1)
                  }
                >
                  <i className='icon'></i>
                </span>
                <span
                  className={classNames('hate', {
                    hated: item.attitude === -1,
                  })}
                  onClick={() =>
                    this.handleLike(item.id, item.attitude === -1 ? 0 : -1)
                  }
                >
                  <i className='icon'></i>
                </span>
                <span
                  className='reply btn-hover'
                  onClick={() => this.handleClick(item.id)}
                >
                  删除
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>
    )
  }
}
